﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using RooHui.Tool;

namespace RooHui.Application.CommonWebLogic
{
    public class CriticalRegion : IDisposable
    {
        private static object commonKey = new object();
        private static Dictionary<string, object> projectKey = new Dictionary<string, object>();

        private string scopeKey = string.Empty;
        public CriticalRegion(string scopeKey)
        {
            this.scopeKey = scopeKey;
            if (!projectKey.ContainsKey(scopeKey))
            {
                lock (commonKey)
                {
                    if (!projectKey.ContainsKey(scopeKey))
                    {
                        projectKey.Add(scopeKey, new object());
                    }
                }
            }
        }
        public bool Set()
        {
            var key = projectKey[scopeKey];
            if (key == null)
            {
                return false;
            }
            try
            {
                //60s 获取锁等待超时
                return Monitor.TryEnter(key, 60000);
            }
            catch (Exception e)
            {
                LogHelper.Write(CommonLogger.Web, LogLevel.Error, e);
            }
            return false;
        }
        public void Dispose()
        {
            var key = projectKey[scopeKey];
            if (key != null)
            {
                try
                {
                    Monitor.Exit(key);
                }
                catch (Exception e)
                {
                    LogHelper.Write(CommonLogger.Web, LogLevel.Error, e);
                }
            }
        }
    }
}
